package TCP和UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private int port;
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true) {
            //1.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            //当receive完成之后数据是以二进制形式存储在DatagramPacket中
            //要想把这个数据给显示出来还需要把这个数据给转换成字符串
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());

            //2.根据请求计算响应(一般服务器都会经历的过程)
            //由于是回显服务器，请求是啥响应就是啥
            String response = process(request);
            //3.把响应写回客户端，构造一个对象，DatagramPacket
            //往DatagramPacket 里构造刚才的数据，在通过send返回
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);

            //4.打印一个日志，把这次数据的交互详情给打印出来
            System.out.printf("[%s:%d] req = %s, resp = %s\n", requestPacket.getAddress().toString(),
                    requestPacket.getPort(), request, response);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(8080);
        udpEchoServer.start();
    }
}
